<template>
	<div class="login">
		<div class="xm">
			<img src="@/assets/xm.png" alt="" srcset="">
		</div>
		<el-form class="login" :model="user" status-icon :rules="rules" ref="ruleForm"  >
			<el-form-item  prop="userName">
				<el-input v-model="user.userName" autocomplete="off" placeholder="请输入你的账户"></el-input>
			</el-form-item>
			<el-form-item  prop="password">
				<el-input type="password" v-model="user.password" autocomplete="off" placeholder="请输入你的密码"></el-input>
			</el-form-item>

			<el-form-item>
				<el-button style="width:100%" type="primary" @click="submitForm('ruleForm')">用户登录</el-button>
			</el-form-item>
		</el-form>
	</div>
</template>

<script>
import { mapState ,mapMutations} from "vuex";
	export default {
		data() {
			return {
				user: {
					userName: '',
					password: ''
				},
				rules: {
					userName: [{
						required: true,
						message: '必填项',
						trigger: ['blur', 'change']
					}, ],
					password:[{
						required: true,
						message: '必填项',
						trigger: ['blur', 'change'],
						}
					]

				}
			}
		},methods:{
			...mapMutations(['changeToken','setUserinfo']),
			submitForm(formName){
				this.$refs[formName].validate((valid) => {
					if (valid) {
						//实现登录的业务
						this.login(this.user.userName,this.user.password)

					} else {
						console.log('error submit!!');
						return false;
					}
				});
			},
			login(userName,password){
				this.$axios.post('/api/userinfo/login',{
					userName:userName,
					password:password
				}).then(res=>{
					//访问成功
					//保存token
					if(res.data.success){
						let token=res.data.data.userinfo.token;
						this.changeToken(token);
						//保存用户信息
						this.setUserinfo(res.data.data.userinfo)
						
						this.$router.push("/my")	
					}

				}).catch(err=>{
					//访问失败
					console.log(err)
				})



			}
		}

	}
</script>

<style>
.xm{
	height: 250px;
	display: flex;
	justify-content: center;
	align-items: center;
	border-bottom: 1px solid #ccc;
}
.login{
	margin-top: 20px;
}
</style>
